package org.shiro.web;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 用户操作Servlet
 * Created by Administrator on 2016/11/21.
 */
@WebServlet(name = "userAddServlet", urlPatterns = "/userAdd")
public class UserAddServlet extends HttpServlet {

    protected PasswordService passwordService = new DefaultPasswordService();

    /**
     * doGet直接跳转到登录界面
     * */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/userAdd.jsp").forward(req, resp);
    }

    /**
     * doPost请求执行用户验证
     * */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取表单信息
        String error = null;
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String encrypt = passwordService.encryptPassword(password);

        // 存储进数据库
        Connection con = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shiro?useSSL=true", "root", "root");
            ps = con.prepareStatement("insert into users values('" + username + "','" + encrypt + "', null)");
            ps.execute();
        } catch (Exception e) {
            error = "添加用户错误";
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                con.close();
            } catch (SQLException e) {
                error = "关闭jdbc错误";
                e.printStackTrace();
            }
        }

        if(error != null) {//出错了，返回登录页面
            req.setAttribute("error", error);
            req.getRequestDispatcher("/WEB-INF/jsp/useAdd.jsp").forward(req, resp);
        } else {//登录成功
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }
}